import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:s_mankey/config/resource_mananger.dart';
import 'package:s_mankey/config/router_config.dart';
import 'package:s_mankey/generated/I18n.dart';
import 'package:s_mankey/model/search_article_model.dart';
import 'package:s_mankey/service/smonkey_repository.dart';
import 'package:s_mankey/ui/widget/error_widget.dart';
import 'package:s_mankey/ui/widget/loading_widget.dart';
import 'package:s_mankey/view_model/search_vm.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class HomeSearch extends StatefulWidget {
  @override
  _HomeSearch createState() => _HomeSearch();
}

class _HomeSearch extends State<HomeSearch> {
  bool showResults = false; //显示搜索结果
  TextEditingController _controller = TextEditingController();
  String keyword;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        body: Container(
          margin: EdgeInsets.fromLTRB(0, 20, 0, 20),

          child: ListView(
            shrinkWrap: true,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      height: 40,
                      decoration: BoxDecoration(
                          color: AppColor.SerchBarColor,
                          borderRadius:
                              BorderRadius.all(Radius.circular(30))),
                      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                      child: Row(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(right: 10),
                            child: Icon(
                              Icons.search,
                              size: 18,
                            ),
                          ),
                          Expanded(
                            child: TextField(
                              autofocus: true,
                              controller: _controller,
                              //编辑框的控制器，跟文本框的交互一般都通过该属性完成，如果不创建的话默认会自动创建
                              onChanged: (text) {
                                Provider.of<SearchVM>(context)
                                    .onChangedText(text: text);
                              },
                              onSubmitted: (text) {
                                keyword = text;
                                showResults = true;
                                setState(() {});
                              },
                              decoration: InputDecoration(
                                contentPadding: EdgeInsets.only(bottom: 9),
                                border: InputBorder.none,
                                hintText: '搜索内容',
                                hintStyle:
                                    TextStyle(fontSize: AppFontSize.Size16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),

                  setRightText(context), //取消按钮
                ],
              ),
//                setDetails(context),
              _setImageDetail(
                  context: context,
                  showResults: showResults,
                  keyword: keyword),
            ],
          ),
        ));
  }
}

/// 取消
Widget setRightText(BuildContext context) {
  return Padding(
    padding: EdgeInsets.only(left: 10),
    child: GestureDetector(
      onTap: () {
        Navigator.of(context).pop();
      },
      child: Text(
        '取消',
        style: TextStyle(fontSize: AppFontSize.Size16, color: Colors.grey),
      ),
    ),
  );
}


/// 搜索结果
Widget _setImageDetail(
    {BuildContext context, bool showResults, String keyword}) {
  debugPrint('keyword##${keyword}');
  return !showResults
      ? Text('')
      : FutureBuilder(
          future: SmonkeysRepository.fetchHomeCourse(keyword: keyword),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            /// 请求中
            if (snapshot.connectionState != ConnectionState.done) {
              return LoadingWidget();
            }

            /// 请求结束, 错误
            if (snapshot.hasError) {
              // 请求失败，显示错误
              return unLoginErrorTip(
                errorTip: snapshot.error.toString(),
                context: context,
              );
            }

            List<SearchArticleModel> datas;
            if(snapshot.data.length <= 0) {
              datas = null;
            } else {
              datas = snapshot.data
                  .map<SearchArticleModel>(
                      (item) => SearchArticleModel.fromJson(item))
                  .toList();
            }
            /// 请求成功，显示数据
            return 
              (datas == null)
                ? Text('')
                :
                    ListView.builder(
                      physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: datas.length,
                        itemBuilder: (context, index) {
                          return
                            Container(
                              decoration: BoxDecoration(border: Border(bottom: BorderSide(color: AppColor.dividerColor))),
                          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                          child: GestureDetector(
                            onTap: () {
                              print('跳到了第${index}详情页');
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                ClipRRect(
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(AppPadding.Padding5)),
                                  child: Image.network(
                                    datas[index].typePhotoLink,
                                    fit: BoxFit.fill,
                                    width: 83,
                                    height: 103,
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Padding(
                                          padding: EdgeInsets.fromLTRB(
                                              10, 0, 10, 10),
                                          child: Text(
                                            datas[index].courseName,
                                            overflow: TextOverflow.clip,
                                            softWrap: true,
                                            maxLines: 1,
                                            style: TextStyle(
                                                fontSize: AppFontSize.Size16,
                                                color: Colors.black),
                                          ),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(
                                              left: AppPadding.Padding10),
                                          child: Text(
                                            datas[index].typeShortDesc,
                                            overflow: TextOverflow.clip,
                                            softWrap: true,
                                            style: TextStyle(
                                                fontSize: AppFontSize.Size14,
                                                color: Color(0xff747474)),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),);
                        });
          });
}
